<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 卡密管理
 *
 * @icon fa fa-circle-o
 */
class Kami extends Backend
{

    /**
     * Kami模型对象
     * @var \app\admin\model\Kami
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Kami;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    
     /**
      * 批量添加卡密 
      * 接收卡密参数一行一个
      */
    public function batchadd()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
    
        $params = $params['kami'];
        $params = is_array($params) ? implode("\n", $params) : $params;
    
        // 将参数按换行符分割成数组
        $cardKeys = preg_split("/\r\n|\n|\r/", $params);
    
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $dataLimitField = $this->dataLimitField;
            $authId = $this->auth->id;
        }
    
        $successCount = 0;
        $existsCount = 0;
        // return $cardKeys;
        foreach ($cardKeys as $key => $val) {
            // 去除首尾空格和换行符
            $val = trim($val);
            if (!empty($val)) {
                $exists = $this->model->where('kami', $val)->find();
                if ($exists) {
                    // 如果存在重复值，跳过当前循环
                    $existsCount++;
                    continue;
                }
                $data[$key]['kami'] = $val;
                $data[$key]['status'] = '0'; // 设置默认 status 为 0
            }
        }

        if (isset($dataLimitField) && !empty($dataLimitField)) {
            $data[$dataLimitField] = $authId;
        }

        $result = $this->model->validate(true)->allowField(true)->saveAll($data);
        // var_dump($result);
        $successCount = count($data);

        if ($result !== false) {
            $this->success('批量添加成功，成功添加'.$successCount.'条数据,'.$existsCount.'条重复');
        } else {
            $this->error(__('No rows were inserted'));
        }

        $this->success();
    }

}
